import logging
import requests, re

from functools import partial
_LOGGER = logging.getLogger(__name__)

#  第三个版本
class tyReboot:
    # 初始化
    def __init__(self, hass, entry, ip, user, pwd):
        self.hass = hass
        self.entry = entry
        self.ip = ip
        self.user = user
        self.pwd = pwd

    # 登陆
    async def login(self):
        url = f"http://{self.ip}/cgi-bin/luci"

        payload=f'username={self.user}&psd={self.pwd}'  # 用户名密码
        headers = {
        'Host': f'{self.ip}',
        'Content-Length': '28',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'Origin': f'http://{self.ip}',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Referer': f'http://{self.ip}/cgi-bin/luci',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive'
        }

        try:# 
            request_func = partial(requests.post, url, headers=headers, data=payload, allow_redirects=False)  # 禁止自动重定向,以便于获取cookies             
            response = await self.hass.async_add_executor_job(request_func)
            cookies = response.cookies
            cookie = requests.utils.dict_from_cookiejar(cookies)
            request_func = partial(requests.post, url, headers=headers, data=payload, cookies=cookie)             
            response = await self.hass.async_add_executor_job(request_func)
            matchObj = re.search(r'([a-z]|[0-9]){32}', str(response.text))
            return matchObj.group(), cookies['sysauth']      
        except Exception as err:
            _LOGGER.error('Cannot log in:\n{0}'.format(err))
            return None, None

    # 重启
    async def reboot(self, token, cookie):
        url = f"http://{self.ip}/cgi-bin/luci/admin/reboot"

        payload='token=' + str(token) + '&t=123'
        headers = {
        'content-type': 'application/x-www-form-urlencoded',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'Origin': f'http://{self.ip}',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Referer': f'http://{self.ip}/cgi-bin/luci',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Cookie': 'sysauth=' + str(cookie)
        }

        request_func = partial(requests.post, url, headers=headers, data=payload)  # 禁止自动重定向,以便于获取cookies             
        response = await self.hass.async_add_executor_job(request_func)
        return response.text

 
